package org.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.TimerTask;

// 修复状态
public class RepairState implements GameState {
    private final CodeRebirthGame game;
    private JTextArea codeArea;
    private JLabel challengeLabel;
    private JLabel scoreLabel;
    private int score = 0;
    private int progress = 0;
    private Timer progressTimer;
    private boolean showProgress = false;

    public RepairState(CodeRebirthGame game) {
        this.game = game;
    }

    @Override
    public void enter() {
        game.setLayout(new BorderLayout());

        // 挑战面板
        JPanel challengePanel = new JPanel(new BorderLayout());
        challengePanel.setBackground(new Color(0, 0, 255, 100)); // 40%透明蓝色
        challengePanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        challengeLabel = new JLabel(
                "<html><div style='width:600px;color:white;font-weight:bold;'>" +
                        "修复挑战 #1: 修复下面的代码错误" +
                        "</div></html>"
        );
        challengePanel.add(challengeLabel, BorderLayout.CENTER);

        // 代码编辑区
        codeArea = new JTextArea();
        codeArea.setFont(game.getResourceManager().getFont("code", 16f));
        codeArea.setBackground(Color.BLACK);
        codeArea.setForeground(new Color(150, 255, 150)); // 荧光绿
        codeArea.setCaretColor(Color.WHITE);
        codeArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 底部按钮面板
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.setBackground(Color.BLACK);

        // 左侧积分显示
        JPanel leftPanel = new JPanel();
        leftPanel.setOpaque(false);
        scoreLabel = new JLabel("积分: " + score);
        scoreLabel.setForeground(Color.WHITE);
        leftPanel.add(scoreLabel);

        // 右侧按钮
        JPanel rightPanel = new JPanel();
        rightPanel.setOpaque(false);

        JButton saveBtn = new JButton("保存进度");
        styleButton(saveBtn);
        saveBtn.addActionListener(e -> game.getPlayerData().saveGame());

        JButton hintBtn = new JButton("提示 (10积分)");
        styleButton(hintBtn);
        hintBtn.addActionListener(e -> {
            if (score >= 10) {
                score -= 10;
                scoreLabel.setText("积分: " + score);
                showMessage("提示: 检查变量命名是否正确");
            } else {
                showMessage("积分不足!");
            }
        });

        JButton submitBtn = new JButton("提交");
        styleButton(submitBtn);
        submitBtn.addActionListener(e -> checkAnswer());

        rightPanel.add(saveBtn);
        rightPanel.add(Box.createHorizontalStrut(10));
        rightPanel.add(hintBtn);
        rightPanel.add(Box.createHorizontalStrut(10));
        rightPanel.add(submitBtn);

        bottomPanel.add(leftPanel, BorderLayout.WEST);
        bottomPanel.add(rightPanel, BorderLayout.EAST);

        // 添加到主界面
        game.add(challengePanel, BorderLayout.NORTH);
        game.add(new JScrollPane(codeArea), BorderLayout.CENTER);
        game.add(bottomPanel, BorderLayout.SOUTH);
    }

    private void checkAnswer() {
        String answer = codeArea.getText().trim();
            if (answer.contains("System.out.println")) {
                game.getPlayerData().completeRepair();
                showProgressBar();
            }

        // 简单模拟答案检查
        if (answer.contains("System.out.println")) {
            // 答案正确
            score += 20;
            scoreLabel.setText("积分: " + score);
            showProgressBar();
        } else {
            // 答案错误
            game.changeState(new AlertState(game));
        }
    }

    private void showProgressBar() {
        progressTimer = new Timer();
        progressTimer.setRepeats(new TimerTask() {
            @Override
            public void run() {
                progress += 5;
                if (progress >= 100) {
                    this.cancel();
                    if (game.getPlayerData().getRepairProgress() >= 100) {
                        game.changeState(new FinalTextState(game) {
                            @Override
                            public void render() {

                            }
                        });
                    } else {
                        game.changeState(new RepairState(game));
                    }
                }
                game.repaint();
            }
        }, 0, 400);
    }
    private void styleButton(JButton button) {
        button.setFont(game.getResourceManager().getFont("main", 14f));
        button.setBackground(new Color(70, 130, 180));
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
    }

    private void showMessage(String msg) {
        JOptionPane.showMessageDialog(game, msg);
    }

    @Override
    public void render(Graphics g) {
        if (showProgress) {
            // 绘制进度条
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, game.getWidth(), game.getHeight());

            // 进度条背景
            g.setColor(Color.GRAY);
            int barWidth = 600;
            int barHeight = 30;
            g.fillRect((game.getWidth()-barWidth)/2, game.getHeight()/2 - 50, barWidth, barHeight);

            // 进度条前景
            g.setColor(Color.BLUE);
            g.fillRect((game.getWidth()-barWidth)/2, game.getHeight()/2 - 50, barWidth * progress / 100, barHeight);

            // 进度文本
            g.setColor(Color.WHITE);
            g.setFont(game.getResourceManager().getFont("title", 24f));
            String text = "修复进度: " + progress + "%";
            int textWidth = g.getFontMetrics().stringWidth(text);
            g.drawString(text, (game.getWidth()-textWidth)/2, game.getHeight()/2 + 50);
        }
    }

    @Override public void update() {}

    @Override
    public void exit() {
        if (progressTimer != null) progressTimer.cancel();
        game.getContentPane().removeAll();
    }

    @Override public void handleInput(KeyEvent e) {}
    private void showProgressBar() {
        progressTimer = new Timer();
        progressTimer.schedule(new TimerTask() { // 修正Timer使用方式
            @Override
            public void run() {
                progress += 5;
                if (progress >= 100) {
                    this.cancel();
                    if (game.getPlayerData().getRepairProgress() >= 100) {
                        game.changeState(new FinalTextState(game));
                    } else {
                        game.changeState(new RepairState(game));
                    }
                }
                game.repaint();
            }
        }, 0, 400);
    }
}
